"""
标准格式的pymysql链接数据库
"""
from pymysql import Connection

conn = None
cursor = None
try:

    # 1. 创建数据库连接对象
    conn = Connection(
        user="root",
        password="root",
        host="localhost",
        database="db03",
        port=3306,
        charset="utf8",
    )
    # print(conn)
    # print(type(conn))
    # print(conn.host_info) # 连接详细信息
    # 2. 创建游标对象
    cursor = conn.cursor()

    # 3. 调用游标对象的方法执行SQL
    # 创建数据表
    sql = '''
        CREATE TABLE hero(
            id INT PRIMARY KEY AUTO_INCREMENT,
            h_name VARCHAR(30),
            age INT,
            gender VARCHAR(5),
            address VARCHAR(100)
        )
    '''
    cursor.execute(sql)
    # 4. 数据库连接对象 将数据提交到数据库或者处理数据
    conn.commit()
except Exception as e:
    print(e)
finally:
    # 5. 关闭游标对象
    if cursor:
        cursor.close()
    # 6. 关闭数据库连接对象
    if conn:
        conn.close()
